import axios from 'axios';
import { useUserStore } from '@/pinia/user.js';
import { MessagePlugin,DialogPlugin } from 'tdesign-vue-next';

const alert = (message, type = 'error') => {
    MessagePlugin({
        content: message,
        theme: type
    })
}

// 配置新建一个 axios 实例
const service = axios.create({
    baseURL: import.meta.env.VITE_APP_API,
    withCredentials: true,
    timeout: 50000,
    headers: { 'Content-Type': 'application/json;charset=utf-8' }
});

// 添加请求拦截器
service.interceptors.request.use(
    (config) => {
        const userStore = useUserStore();
        if (userStore.token) {
            config.headers['Authorization'] = 'Bearer ' + userStore.token;
        }
        return config
    },
    (error) => {
        return Promise.reject(error);
    }
);

// 添加响应拦截器
service.interceptors.response.use(
    (response) => {
        const { config, data, headers } = response
        // 响应数据为二进制流处理(Excel导出)
        if (data instanceof ArrayBuffer) {
            return response;
        }
        if (data?.code !== 0 && data?.message) {
            alert(data.message)
        }
        return data;
    },
    (error) => {
        if (error.response && error.response?.status) {
            const userStore = useUserStore();
            const { errMessage, status } = error.response.data
            switch (error.response?.status) {
                case 400: {
                    alert(errMessage || "400：内部错误，请联系管理员")
                    break
                }
                case 403: {
                    if (status === '40300000001') {
                        alert(errMessage || '暂无权限')
                    } else if (status === '40300000003') {
                        DialogPlugin.confirm({
                            header: '提示',
                            body: '当前页面已失效，请重新登录',
                            confirmBtn: {
                                content: '提交',
                                theme: 'primary',
                                loading: false,
                            },
                            theme: 'warning',
                            onConfirm: () => {
                                userStore.logOut()
                            },
                        });
                    }
                    break
                }
                case 422: {
                    alert(errMessage || "未知错误")
                    break
                }
                case 500: {
                    alert(errMessage || "500：该操作服务器内部错误。")
                    break;
                }
                case 504: {
                    alert(errMessage || "504：服务器未连接，请检查服务状态。")
                    break;
                }
                default: {
                    alert(errMessage || `未知错误，错误码：${error.response.status}`)
                }
            }
        }
        return Promise.reject(error);
    }
);

// 导出 axios 实例
export default service;
